﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using System.IO;

using YLClient.Util;
using YLClient.YLServiceReference;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Threading;

namespace YLClient.Froms
{
    /// <summary>
    /// Interaction logic for NewItem.xaml
    /// </summary>
    public partial class NewItem : Window
    {
        ClientAdapter client;
        List<string> errorFiles;
        public NewItem()
        {
            InitializeComponent();

            initialUI();

            errorFiles = new List<string>();
            client = new ClientAdapter();
            client.OnTransfefMoveNext += new TransfefMoveNext(client_OnTransfefMoveNext);
            client.OnTransferError += new TransferFileError(client_OnTransferError);
        }

        void client_OnTransferError(string fileName)
        {
            errorFiles.Add(fileName);
        }


        void client_OnTransfefMoveNext(string preFileName, double precent)
        {
            //使用Dispatcher实现异步更新控件
            Action<double> update = v => progressBar.Value = v;
            Dispatcher.Invoke(
                update
                , DispatcherPriority.ApplicationIdle
                , precent
            );


        }

        private void initialUI()
        {
            var cmdBinding = new CommandBinding(ApplicationCommands.Delete, deleteItems);
            lstFileNames.CommandBindings.Add(cmdBinding);
            //获取模板列表
            string[] templates = (string[])GlobalClass.DataContainer.Dict["ItemTemplates"];
            if (templates == null)
            {
                templates = GlobalClass.DataContainer.Client.GetTemplates(GlobalClass.DataContainer.Guid);
            }
            cmbTemplateName.ItemsSource = templates;
        }




        private void deleteItems(object sender, ExecutedRoutedEventArgs arg)
        {
            var src = btnDataContainer.Content as List<string>;
            if (sender is ListBox)
            {
                ListBox lst = (ListBox)sender;
                switch ((string)arg.Parameter)
                {
                    case "single":
                        var item = lst.SelectedItem as string;
                        src.Remove(item);
                        lst.Items.Refresh();
                        break;
                    case "all":
                        src.Clear();
                        lst.Items.Refresh();
                        break;
                    default:
                        break;
                }
            }
        }

        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            timePick.Time = DateTime.Now;

        }


        /// <summary>
        /// 获取拖拽上来的所有文件全路径名
        /// </summary>
        /// <param name="pathes"></param>
        /// <returns></returns>
        private List<string> getFilesFromDragDrop(string[] pathes)
        {
            var ret = pathes.SelectMany(
                path =>
                {
                    if (path.Contains('.'))
                        return singleToIEnumerable(path);
                    else
                    {
                        return Common.getDirFiles(path);
                    }
                }).ToList();
            return ret;
        }

        private IEnumerable<T> singleToIEnumerable<T>(T o)
        {
            yield return o;
        }

        private void btnCancel_Click(object sender, RoutedEventArgs e)
        {
            var ret = MessageBox.Show("是否退出？", "帮助", MessageBoxButton.YesNo);
            if (ret == MessageBoxResult.Yes)
            {
                this.Close();
            }
        }

        //drag enter的时候拷贝btnDataContainer.Content，
        //如果发生drag leave 那么用此值赋予btnDataContainer.Content
        private List<string> tempFiles;
        /// <summary>
        /// 上传新的drag项
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Window_DragEnter(object sender, DragEventArgs e)
        {
            if (e.Data.GetDataPresent(DataFormats.FileDrop))
            {
                tempFiles = btnDataContainer.Content as List<string>;
                e.Effects = DragDropEffects.Link;
                String[] pathes = e.Data.GetData(DataFormats.FileDrop) as string[];
                var files = getFilesFromDragDrop(pathes);

                if (btnDataContainer.Content != null)
                {
                    var first = (List<string>)btnDataContainer.Content;
                    var temp = files.Union(first).ToList();
                    temp.Sort();
                    btnDataContainer.Content = temp;
                }
                else
                {
                    files.Sort();
                    btnDataContainer.Content = files;
                }
            }
        }
        private void Window_DragLeave(object sender, DragEventArgs e)
        {
            btnDataContainer.Content = tempFiles;
        }

        private string[] getUploadFiles()
        {
            return lstFileNames.Items.Cast<string>().ToArray();
        }

        private void btnAdd_Click(object sender, RoutedEventArgs e)
        {

            #region UI控制
            btnAdd.IsEnabled = false;
            #endregion

            #region 数据初始化
            errorFiles.Clear();
            #endregion

            //将要上传的文件名字列表
            var files = getUploadFiles();

            if (true == checkAllValue() && files.Count() > 0) //判断信息是否填写完毕
            {
                #region 初始化WorkItem
                WorkItem item = new WorkItem();
                item.TemplateName = cmbTemplateName.SelectedValue.ToString();
                item.boyName = txtbBoy.Text;
                item.grilName = txtbGril.Text;
                item.Time = timePick.Time;
                #endregion

                txtbStatus.Text = "开始压缩图片......";
                progressBar.Value = 100;
                Task<string> imgTask = new Task<string>(() =>
                {
                    #region 压缩图片
                    ImageProcessHelper imgProcesser = new ImageProcessHelper();
                    return imgProcesser.CompressImages(files);//耗时操作
                    #endregion
                });
                imgTask.ContinueWith(
                    imgt =>
                    {
                        txtbStatus.Text = "图片压缩完成,开始上传图片......";
                        progressBar.Value = 0;
                        var cmpFilesDir = imgTask.Result;
                        var compressFiles = Common.getDirFiles(cmpFilesDir);

                        if (!client.AddWorkItemParallel(item, compressFiles, 0.3))//上传工作项，数据库上传和ftp上传
                        {
                            MessageBox.Show("上传过程出错！", "错误");
                        }
                        else
                        {
                            //设置按钮的content为空就是的文件列表清空。因为他们之间存在绑定
                            btnDataContainer.Content = null;
                            lstFileNames.UpdateLayout();
                            if (errorFiles.Count > 0)
                            {
                                MessageBox.Show("传输过程中存在失败文件，请再次上传...", "提示");
                                errorFiles.ToList().ForEach(file => lstFileNames.Items.Add(file));
                            }
                        }
                        //删除传输成功的临时文件
                        var successTransferFiles = compressFiles.Except(errorFiles);
                        foreach (var file in successTransferFiles)
                        {
                            File.Delete(file);
                        }
                        //一切正常，提示成功然后关闭
                        txtbStatus.Text = "准备就绪";
                        btnAdd.Content = "继续上传";
                        progressBar.Value = 0;
                    },
                   TaskScheduler.FromCurrentSynchronizationContext() //因为上面方法中使用到了U上的控件.如果使用dispatcher也是可行的
               );
                imgTask.Start();
            }
            else
            {
                MessageBox.Show("红色星号为必填项", "提示");
            }

            btnAdd.IsEnabled = true;
        }
        /// <summary>
        /// 判断信息填写完善
        /// </summary>
        /// <returns></returns>
        private bool checkAllValue()
        {
            return
                txtbBoy.Text != string.Empty
                && txtbGril.Text != string.Empty
                && cmbTemplateName.SelectedValue != null;
        }
    }
}
